﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using STX.Admin.Models.BizNotice;
using STX.Domain;
using STX.Service;

namespace STX.Admin.Controllers
{
    public class BizNoticeController : BasePages1Controller<BizNotice,IndexModel,AddModel,EditModel,QueryModel>
    {
        public BizNoticeService BizNoticeService { get; set; }


        protected override void OnInit(out Func<BaseService<BizNotice>> thisService, out Func<IndexModel> getIndexModelFunc, out Func<AddModel> getAddModelFunc, out Func<int, EditModel> getEditModelFunc)
        {
            thisService = () => BizNoticeService;
            getIndexModelFunc = () => new IndexModel();
            getAddModelFunc = () => new AddModel();
            getEditModelFunc = id =>
            {
                var model = BizNoticeService.FindModelById(id);
                if (model == null) {
                    throw new Exception("此数据可能已被删除");
                }
                return new EditModel
                {
                    Id = id,
                    Content = model.Content,
                    Title = model.Title
                };
            };

        }

        protected override long AddHandler(AddModel addModel)
        {
            var model = new BizNotice
            {
                 AddTime = DateTime.Now,
                 Content = addModel.Content,
                 Title=addModel.Title
            };
            return BizNoticeService.Add(model);
        }

        protected override bool EditHandler(EditModel editModel)
        {
            var model = BizNoticeService.FindModelById(editModel.Id);
            if (model == null) {
                throw new Exception("此数据可能已被删除");
            }
            model.Title = editModel.Title;
            model.Content = editModel.Content;
            return BizNoticeService.Update(model);
        }

        protected override IQueryable<BizNotice> QueryHandler(QueryModel queryModel, IQueryable<BizNotice> queryable)
        {
            if (!queryModel.Name.IsNullOrEmpty())
                queryable = queryable.Where(o => o.Title.Contains(queryModel.Name));
            return queryable;
        }

        public ActionResult Detail(int id)
        {
            var model = BizNoticeService.FindModelById(id);
            if (model == null)
            {
                throw new Exception("此数据可能已被删除");
            }
            var dto = new EditModel
            {
                Id = id,
                Content = model.Content,
                Title = model.Title,
                AddTime = model.AddTime
            };
            return View(dto);
        }
    }
}
